package chapter20.annotations.database;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class TableCreator {
	public static void create(String[] classNames) throws Exception{
		if(classNames == null || classNames.length < 1)
			return;
		for(String className: classNames) {
			Class<?> cl = Class.forName(className);
			DBTable dbTable = cl.getAnnotation(DBTable.class);
			if(dbTable == null) {
				System.out.println("No DBTable annotions in class " + className);
			   continue;
			}
			String tableName = dbTable.name();
			if(tableName.length() < 1)
				tableName = cl.getName().toUpperCase();
			List<String> columnDefs = new ArrayList<>();
			for(Field field: cl.getDeclaredFields()) {
				String columnName = null;
				Annotation[] anns = field.getDeclaredAnnotations();
				if(anns.length < 1)
					continue;
				if(anns[0] instanceof SQLInteger) {
					SQLInteger sInt = (SQLInteger)anns[0];
					if(sInt.name().length() < 1)
						columnName = field.getName().toUpperCase();
					else
						columnName = sInt.name();
					columnDefs.add(columnName + " INT" + getConstraints(sInt.constraints()));
				}
				
				if(anns[0] instanceof SQLString) {
					SQLString sString = (SQLString)anns[0];
					if(sString.name().length() < 1)
						columnName = field.getName().toUpperCase();
					else
						columnName = sString.name();
					columnDefs.add(columnName + " VARCHAR(" + sString.value() + 
							")" + getConstraints(sString.constraints()));
				}
				StringBuilder createCommand = new StringBuilder("create table " +
				  tableName + " (");
				for(String columnDef: columnDefs) 
					createCommand.append("\n    " + columnDef + ",");
				String tableCreate = createCommand.substring(0, createCommand.length() - 1) + ")";
				System.out.println("Table Creation SQL for " + className + " is: \n" + tableCreate);
			}
		}
		
	}
	
	public static String getConstraints(Constraints conn) {
		String constraints = "";
		if(conn.allowNull())
			constraints += " NOT NULL";
		if(conn.primaryKey())
			constraints += " PRIMARY KEY";
		if(conn.unique())
			constraints += " UNIQUE";
		return constraints;
	}
	
	public static void main(String[] args) throws Exception {
		create(new String[]{"chapter20.annotations.database.Member"});
	}
}
